<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title>编辑商品 - 优选商城</title>
    <style th:fragment="styles">
        .preview-image {
            width: 200px;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
            margin: 10px;
        }
        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="container-fluid py-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>编辑商品</h2>
                <a href="/admin/products" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> 返回列表
                </a>
            </div>

            <div class="card">
                <div class="card-body">
                    <form id="productForm" class="needs-validation" novalidate>
                        <input type="hidden" name="id" th:value="${product.id}">
                        <input type="hidden" name="categoryId" th:value="${product.categoryId}">
                        
                        <div class="row">
                            <div class="col-md-8">
                                <!-- 基本信息 -->
                                <div class="mb-4">
                                    <h5>基本信息</h5>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">商品名称</label>
                                            <input type="text" class="form-control" name="name" th:value="${product.name}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品副标题</label>
                                            <input type="text" class="form-control" name="subtitle" th:value="${product.subtitle}">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品分类</label>
                                            <select class="form-select" id="categoryId" name="categoryId" required>
                                                <option value="">请选择分类</option>
                                                <option th:each="category : ${categories}"
                                                        th:value="${category.id}"
                                                        th:text="${category.name}">
                                                    分类
                                                </option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品价格</label>
                                            <input type="number" class="form-control" name="price" th:value="${product.price}" step="0.01" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">库存数量</label>
                                            <input type="number" class="form-control" name="stock" th:value="${product.stock}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品状态</label>
                                            <select class="form-select" name="status">
                                                <option value="1" th:selected="${product.status == 1}">上架</option>
                                                <option value="0" th:selected="${product.status == 0}">下架</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- 商品图片 -->
                                <div class="mb-4">
                                    <h5>商品图片</h5>
                                    <div class="mb-3">
                                        <label class="form-label">主图</label>
                                        <input type="file" class="form-control" id="mainImage" accept="image/*">
                                        <div class="image-preview-container">
                                            <img id="mainImagePreview" class="preview-image" th:src="${product.mainImage}">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">子图（可多选）</label>
                                        <input type="file" class="form-control" id="subImages" accept="image/*" multiple>
                                        <div class="image-preview-container" id="subImagesPreview">
                                            <img th:each="image : ${#strings.arraySplit(product.subImages, ',')}" 
                                                 th:src="${image}" 
                                                 class="preview-image">
                                        </div>
                                    </div>
                                </div>

                                <!-- 商品详情 -->
                                <div class="mb-4">
                                    <h5>商品详情</h5>
                                    <textarea class="form-control" name="detail" rows="5" th:text="${product.detail}"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="text-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> 保存修改
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script th:fragment="scripts">
        // 加载商品分类
        function loadCategories() {
            $.get('/api/categories', function(res) {
                if (res.code === 0) {
                    const select = $('select[name="categoryId"]');
                    const currentCategoryId = $('input[name="categoryId"]').val();  // 使用隐藏的分类ID字段
                    res.data.forEach(category => {
                        const selected = category.id == currentCategoryId ? 'selected' : '';
                        select.append(`<option value="${category.id}" ${selected}>${category.name}</option>`);
                    });
                }
            });
        }

        // 图片预览
        function previewImage(input, previewElement) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $(previewElement).attr('src', e.target.result).show();
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        // 多图片预览
        function previewMultipleImages(input, previewContainer) {
            if (input.files && input.files.length > 0) {
                $(previewContainer).empty();
                Array.from(input.files).forEach(file => {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = $('<img>').addClass('preview-image').attr('src', e.target.result);
                        $(previewContainer).append(img);
                    }
                    reader.readAsDataURL(file);
                });
            }
        }

        // 表单提交
        $(document).ready(function() {
            loadCategories();

            // 主图预览
            $('#mainImage').change(function() {
                previewImage(this, '#mainImagePreview');
            });

            // 子图预览
            $('#subImages').change(function() {
                previewMultipleImages(this, '#subImagesPreview');
            });

            // 分类选择变化时更新隐藏字段
            $('select[name="categoryId"]').change(function() {
                $('input[name="categoryId"]').val($(this).val());
            });

            // 表单提交
            $('#productForm').submit(function(e) {
                e.preventDefault();
                
                // 表单验证
                if (!this.checkValidity()) {
                    e.stopPropagation();
                    $(this).addClass('was-validated');
                    return;
                }

                // 构建表单数据
                const formData = new FormData();
                const formFields = $(this).serializeArray();
                formFields.forEach(field => {
                    formData.append(field.name, field.value);
                });

                // 添加图片
                const mainImage = $('#mainImage')[0].files[0];
                if (mainImage) {
                    formData.append('mainImage', mainImage);
                }

                const subImages = $('#subImages')[0].files;
                if (subImages && subImages.length > 0) {
                    Array.from(subImages).forEach(file => {
                        formData.append('subImages', file);
                    });
                }

                // 提交表单
                $.ajax({
                    url: '/admin/products/save',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.code === 0) {
                            showSuccess('保存成功');
                            // 等待提示显示后再跳转
                            setTimeout(function() {
                                window.location.href = '/admin/products';
                            }, 1500);
                        } else {
                            showError(res.msg || '保存失败');
                        }
                    },
                    error: function() {
                        showError('保存失败，请重试');
                    }
                });
            });
        });
    </script>
</body>
</html> 